package ynu.edu.model.utils;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpClientUtil {

    static final int TIMEOUT_MSEC = 30 * 1000;

    /**
     * 发送POST方式请求（普通表单数据）
     * @param url
     * @param jsonString
     * @return
     * @throws IOException
     */

    // 添加新的方法处理JSON请求
    public static String doPost(String url, String jsonString) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";

        try {
            HttpPost httpPost = new HttpPost(url);

            // 设置JSON请求头
            httpPost.setHeader("Content-Type", "application/json");

            // 设置JSON请求体
            StringEntity entity = new StringEntity(jsonString, "UTF-8");
            httpPost.setEntity(entity);

            httpPost.setConfig(builderRequestConfig());

            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } finally {
            if (response != null) {
                response.close();
            }
            httpClient.close();
        }

        return resultString;
    }


    private static RequestConfig builderRequestConfig() {
        return RequestConfig.custom()
                .setConnectTimeout(TIMEOUT_MSEC)
                .setConnectionRequestTimeout(TIMEOUT_MSEC)
                .setSocketTimeout(TIMEOUT_MSEC).build();
    }
}
